local CommonDefine = require("common.CommonDefine")
local Msg = require("core.Msg")
local Human = require("core.Human")
local RoleFFI = require("role.RoleFFI")
local AuthCheck = require("scene.AuthCheck")
local Map = require("core.Map")
local FriendLogic = require("friend.FriendLogic")
local PfLogic = require("tencentApi.PfLogic")
local TencentTaskMarket = require("task.TaskMarket")
local MiddleOpenDB = require("middle.MiddleOpenDB")
local Config = require("Config")
local RoleDBLogic = require("role.RoleDBLogic")
local MiddleDefine = require("middle.MiddleDefine")
local MiddleLogic = require("middle.MiddleLogic")
local BlueLogic = require("tencentApi.BlueLogic")

function CG_AA_DISCONNECT(human)
    if type(human) ~= "table" then return end
    -- print("cg_aa_disconnect:", human.fd, m.reason)
    Human.disconnect(human, CommonDefine.DISCONNECT_NORMAL)
end

function SendDisconnect(fd, reasonCode, reasonStr)
    local mm = Msg.gc.GC_DISCONNECT
    mm.code = reasonCode 
    mm.msg = tostring(reasonStr) or ""
    Msg.send(mm, fd)
end


function CG_ASK_LOGIN(fd, msg)
    if type(fd) ~= "number" then
        assert()
    end

    local account = msg.account
    print("CG_ASK_LOGIN account:", account, " fd:",fd)
    local onlineCnt = 0
    for k in pairs(Human.onlineHuman) do
        onlineCnt = onlineCnt + 1
    end
    if onlineCnt >= CommonDefine.MAX_ONLINE_COUNT then
        SendDisconnect(fd, CommonDefine.DISCONNECT_MAX_ONLINE, "服务器已达到最大人数,请排队或稍后")
        return
    end
    local fcm  = msg.fcm
    local serverid = msg.serverid
    local timestamp = msg.timestamp
    local authkey = msg.authkey   
    
    -- QQ平台相关参数
    local openid  = msg.openid
    local openkey = msg.openkey
    local pf      = msg.pf
    local pfkey   = msg.pfkey
    local yellowYearVip = msg.yellowYearVip
    local yellowVip = msg.yellowVip
    local yellowVipLv = msg.yellowVipLv
    local appContractId = msg.appContractId
    local zoneid = msg.zoneid
    local isMiniClient = msg.isMiniClient
    local x5sig = msg.x5sig
    local blue = msg.blue
    local blueLv = msg.blueLv
    local blueYear = msg.blueYear
    local blueSuper = msg.blueSuper
    local level3366 = msg.level3366
    
    local retAuth = AuthCheck.AuthCheck(account, authkey, timestamp, serverid, fcm, openid, openkey, pf, pfkey, yellowYearVip, yellowVip, yellowVipLv)
    if retAuth ~= true then
        local mm = Msg.gc.GC_DISCONNECT
        mm.code = CommonDefine.DISCONNECT_AUTH_FAIL
        mm.msg = CommonDefine.DISCONNECT_MSG[CommonDefine.DISCONNECT_AUTH_FAIL]
        Msg.send(mm, fd)
        return
    end


    if Config.IS_MIDDLE then
      -- 跨服登录的话要判断帐号数据是否已经存在 这里不允许创建新号
      local ret, data = RoleDBLogic.isAccountExistInDB(account)
      if data == nil or data.middleFlag ~= 1 then
        print("account in normal redirect: ", account, data and data.middleFlag)
        local msgRet = Msg.gc.GC_MIDDLE_LEAVE
        msgRet.result = MiddleDefine.M2G_LOGIN_OK
        msgRet.tip = "ok"
        Msg.send(msgRet, fd)        
        local mm = Msg.gc.GC_DISCONNECT
        mm.code = CommonDefine.DISCONNECT_MIDDLE_NO_DATA
        mm.msg = CommonDefine.DISCONNECT_MSG[CommonDefine.DISCONNECT_MIDDLE_NO_DATA]
        Msg.send(mm, fd)
        return
      end
    else
      -- 正常服登录的话要判断帐号数据是否已经去跨服游戏中了
      local ret, data = RoleDBLogic.isAccountExistInDB(account)
      if data and data.middleFlag == 1 then
        print("account in middle redirect: ", account)
        local msgRet = Msg.gc.GC_MIDDLE_ENTER
        msgRet.result = MiddleDefine.G2M_LOGIN_OK
        msgRet.tip = "ok"
        msgRet.act = 0
        msgRet.copyID = 0
        Msg.send(msgRet, fd)
        local mm = Msg.gc.GC_DISCONNECT
        mm.code = CommonDefine.DISCONNECT_MIDDLEING
        mm.msg = CommonDefine.DISCONNECT_MSG[CommonDefine.DISCONNECT_MIDDLEING]
        Msg.send(mm, fd)
        return 
      end
    end    
    local human_old = Human.onlineAccount[account]
    local db_old
    if human_old then    --踢号
        db_old = human_old.db
        Human.disconnect(human_old, CommonDefine.DISCONNECT_DUPLICATE)
        human_old.db = nil
    end
    local human = Human.create(fd, account, db_old)
    human.pf = pf
    if PfLogic.isAgentTencent() then --QQ平台相关参数
        human.db.pf = pf
        human.db.pfkey = pfkey
        human.db.yellowYearVip = yellowYearVip
        human.db.yellowVip = yellowVip
        human.db.yellowVipLv = yellowVipLv
        human.db.isMiniClient = isMiniClient
        human.db.blueVip = blue
        human.db.blueVipLv = blueLv
        human.db.blueYearVip = blueYear
        human.db.blueSuperVip = blueSuper
        human.db.level3366 = pf == "3366" and level3366 or 0
        human.pf_info = {}
        human.pf_info.openid = openid
        human.pf_info.openkey = openkey
        human.pf_info.pf = pf
        human.pf_info.pfkey = pfkey
        human.pf_info.zoneid = zoneid
        human.pf_info.serverid = serverid     
        human.pf_info.x5sig = x5sig   
        TencentTaskMarket.onTaskMarketLogin(human, appContractId)
        human.pf_info.appContractId = RoleFFI.ffi_string(human.db.appContractId)
        BlueLogic.blueVipInfo(human)
    end
    
    local middleActID = ""
    local middleCopyID = 0
    if Config.IS_MIDDLE and MiddleLogic.NEED_LOGIN_DATA[human._id] then
        middleActID = MiddleLogic.NEED_LOGIN_DATA[human._id].actID
        middleCopyID = MiddleLogic.NEED_LOGIN_DATA[human._id].copyID
        MiddleLogic.NEED_LOGIN_DATA[human._id] = nil
        if not MiddleLogic.middleLogin(human, middleActID, middleCopyID) then 
            MiddleLogic.leave(human) -- 活动结束，或 条件不满足，这里直接返回本服
            return 
        end
    end
    
    Msg.set_logic(human.fd, human._id,Map.get_logic_id(human.db.map_id))
    human.logic_tid = Map.get_logic_id(human.db.map_id)
    local msg = Msg.wl.WL_ASK_LOGIN
    msg.account = account
    msg.id      = human.id
    msg.uid     = human.uid
    msg.fd      = human.fd
    msg.middleActID = middleActID
    msg.middleCopyID = middleCopyID
    Msg.send2logic(msg, human._id)
    print("CG_ASK_LOGIN ok account:", account)
end


-- L线程已处理完协议成功
function LW_ASK_LOGIN_OK(human, m)
  human.scene_id = m.sceneid
  
  human.loginFinish = true
  Human.onLoginIn(human)
  
  --好友设置
  FriendLogic.sendIsAutoAdd(human)
  
  -- 跨服状态
  MiddleOpenDB.sendMiddleOpenMsg(human)
  
  
end


-- L线程已处理完 cg_enter_scene_ok后玩家已进入场景
function LW_ENTER_SCENE_OK(human, m)
  human.scene_id = m.sceneid

  --蓝钻详细信息查询(只能放在这里。。。)
  BlueLogic.blueVipInfo(human, true)
end

function LW_ASK_CHANGE_SCENE(human, m)
    if human.fd == nil then
        return
    end
    if Config.IS_MIDDLE and m.middle == 1 then --跨服回本服
        -- logic已注销
        MiddleLogic.leave(human)
        return 
    end
    Msg.set_logic(human.fd, human._id, Map.get_logic_id(m.map_id))
    human.logic_tid = Map.get_logic_id(m.map_id)
    local msg = Msg.wl.WL_ASK_CHANGE_SCENE
    msg.account = Human.account(human)
    msg.map_id  = m.map_id
    msg.x   = m.x
    msg.y   = m.y
    msg.id  = human.id
    msg.uid = human.uid
    msg.fd = human.fd
    msg.login = human.loginFinish and 0 or 1
    Msg.send2logic(msg, human._id)
    print("LW_ASK_CHANGE_SCENE ok account:", msg.account)
end
function LW_AA_DISCONNECT(human, msg)
    human = Human.onlineAccount[msg.account]
    if human then
        Human.save(human)
    end
    if human and human.fd == nil then
        if msg.code == CommonDefine.DISCONNECT_NORMAL_AFTER then --如果是跨服，需要跳到游戏服
            Human.sendLogoutMiddleData(human)
        end      
        Human.destroy(human)
    end
    print("LW_AA_DISCONNECT:", msg.account)
end
